// 包名与模块引入
package com.example.coffee.provider;
import com.example.coffee.ResourceTable;
import com.example.coffee.items.CaffeeItem;
import com.example.coffee.utils.DisplayUtils;
import ohos.agp.components.*;
import ohos.agp.text.RichTextBuilder;
import ohos.agp.text.TextForm;
import ohos.agp.utils.Color;
import ohos.app.Context;
import java.util.List;
// 类实现
public class ContentListDataProvider extends BaseItemProvider {
    // 数据模型列表
    private List<CaffeeItem> dataList;
    // 上下文对象
    private Context context;
    // 更改数据源
    public void setDataList(List<CaffeeItem> dataList) {
        this.dataList = dataList;
    }
    // 自定义构造方法
    public ContentListDataProvider(List<CaffeeItem> dataList, Context context) {
        this.dataList = dataList;
        this.context = context;
    }
    // 列表项个数
    @Override
    public int getCount() {
        return dataList == null ? 0 : dataList.size();
    }
    // 列表项数据
    @Override
    public Object getItem(int position) {
        if (dataList != null && position >= 0 && position < dataList.size()){
            return dataList.get(position);
        }
        return null;
    }
    // 列表项标识
    @Override
    public long getItemId(int i) {
        return i;
    }
    // 绑定数据
    @Override
    public Component getComponent(int position, Component convertComponent, ComponentContainer componentContainer) {
        final Component cpt;
        if (convertComponent == null) {
            cpt = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_caffee_item, null, false);
        } else {
            cpt = convertComponent;
        }
        // 获取数据模型
        CaffeeItem sampleItem = dataList.get(position);
        // 将组件中的子组件获取到，并进行数据绑定
        Image image = (Image) cpt.findComponentById(ResourceTable.Id_cover);
        image.setPixelMap(sampleItem.getImageId());
        // 设置图片圆角
        image.setCornerRadius(20);
        Text name = (Text) cpt.findComponentById(ResourceTable.Id_caffee_name);
        name.setText(sampleItem.getName());
        Text desc = (Text) cpt.findComponentById(ResourceTable.Id_caffee_desc);
        desc.setText(sampleItem.getDescription());
        Text price = (Text) cpt.findComponentById(ResourceTable.Id_caffee_price);
        price.setText(sampleItem.getPrice());
        Text oriPrice = (Text) cpt.findComponentById(ResourceTable.Id_caffee_ori_pirce);
        // 原价部分采用富文本，对文本增加删除线
        TextForm form = new TextForm();
        form.setStrikethrough(true);
        form.setTextColor(Color.GRAY.getValue());
        form.setTextSize(DisplayUtils.vp2px(context, 15));
        RichTextBuilder builder = new RichTextBuilder(form);
        builder.addText(sampleItem.getOriginalPrice());
        oriPrice.setRichText(builder.build());
        return cpt;
    }
}
